package com.atguigu.tingshu.account.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.IdUtil;
import com.atguigu.tingshu.account.mapper.RechargeInfoMapper;
import com.atguigu.tingshu.account.mapper.UserAccountDetailMapper;
import com.atguigu.tingshu.account.mapper.UserAccountMapper;
import com.atguigu.tingshu.account.service.UserAccountService;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.account.RechargeInfo;
import com.atguigu.tingshu.model.account.UserAccount;
import com.atguigu.tingshu.model.account.UserAccountDetail;
import com.atguigu.tingshu.model.order.OrderInfo;
import com.atguigu.tingshu.model.user.UserInfo;
import com.atguigu.tingshu.order.client.OrderFeignClient;
import com.atguigu.tingshu.vo.account.AccountLockVo;
import com.atguigu.tingshu.vo.account.RechargeInfoVo;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
@SuppressWarnings({"all"})
public class UserAccountServiceImpl extends ServiceImpl<UserAccountMapper, UserAccount> implements UserAccountService {


	@Autowired
	private UserAccountMapper userAccountMapper;

	@Autowired
	private UserAccountDetailMapper userAccountDetailMapper;

	@Autowired
	private OrderFeignClient orderFeignClient;

	@Autowired
	private RechargeInfoMapper rechargeInfoMapper;



	/**
	 * 初始化用户账单
	 * @param userId
	 */
	@Override
	public void initUserAccount(Long userId) {
		//初始用户账单表
		UserAccount userAccount = new UserAccount();
		userAccount.setUserId(userId);
		userAccount.setTotalAmount(new BigDecimal(100));
		userAccount.setTotalIncomeAmount(new BigDecimal(100));
		userAccount.setTotalPayAmount(new BigDecimal(0));

		userAccountMapper.insert(userAccount);

		//更新用户账单明细
		this.insertUserDetail(userId,
				"初始化用户账号，赠送金额100",
				SystemConstant.ACCOUNT_TRADE_TYPE_DEPOSIT,
				new BigDecimal(100),
				null
				);

	}

	/**
	 * 修改用户账户余额
	 * @param accountLockVo
	 */
	@Override
	//@GlobalTransactional(rollbackFor = Exception.class)
	@Transactional(rollbackFor = Exception.class)
	public void checkAndDeduct(AccountLockVo accountLockVo) {

		/**
		 * update user_account set total_amount = total_amount -? ,  available_amount =available_amount -?
		 *                                            , total_pay_amount =total_pay_amount +?
		 *         where user_id =? and available_amount >=?;
		 */
		//扣减账户余额
		int rows = userAccountMapper.updateCheckAndDeduct(accountLockVo.getUserId(),accountLockVo.getAmount());
		if(rows<=0){
			throw new GuiguException(400,"账户扣减失败 余额不足");
		}

		//新增账户明细
		insertUserDetail(
				accountLockVo.getUserId(),
				accountLockVo.getContent(),
				SystemConstant.ACCOUNT_TRADE_TYPE_DEPOSIT,
				accountLockVo.getAmount(),
				accountLockVo.getOrderNo()
		);

	}


	/**
	 * 根据订单号获取充值信息
	 * @param orderNo
	 * @return
	 */
	@Override
	public RechargeInfo getRechargeInfo(String orderNo) {
		RechargeInfo rechargeInfo = rechargeInfoMapper.selectOne(new LambdaQueryWrapper<RechargeInfo>().eq(RechargeInfo::getOrderNo, orderNo));

		return rechargeInfo;
	}


	/**
	 * 充值余额
	 * @param rechargeInfoVo
	 * @return
	 */
	@Override
	public Map<String, String> submitRecharge(RechargeInfoVo rechargeInfoVo) {
		Map<String, String> map = new HashMap<>();
		RechargeInfo rechargeInfo = new RechargeInfo();
		Long userId = AuthContextHolder.getUserId();
		rechargeInfo.setUserId(userId);
		String orderNo = "CZ" + DateUtil.today().replaceAll("-", "") + IdUtil.getSnowflakeNextId();
		rechargeInfo.setOrderNo(orderNo);
		rechargeInfo.setRechargeStatus(SystemConstant.ORDER_STATUS_UNPAID);
		rechargeInfo.setRechargeAmount(rechargeInfoVo.getAmount());
		rechargeInfo.setPayWay(rechargeInfoVo.getPayWay());


		rechargeInfoMapper.insert(rechargeInfo);

		map.put("orderNo",orderNo);
		return map;
	}


	/**
	 * 用户充值，支付成功后，新增余额
	 * @param orderNo
	 * @return
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void rechargePaySuccess(String orderNo) {

		//新增余额
		RechargeInfo rechargeInfo = rechargeInfoMapper.selectOne(new LambdaQueryWrapper<RechargeInfo>().eq(RechargeInfo::getOrderNo, orderNo));
		//用户的充值信息正常不能为空 且不能是支付状态
		if(rechargeInfo !=null && SystemConstant.PAYMENT_STATUS_PAID.equals(rechargeInfo.getRechargeStatus()) ){
			//修改过了
			return;
		}

		//新增余额 根据充值信息获取余额添加到用户账户里
		Long userId = AuthContextHolder.getUserId();
	    int rows =	userAccountMapper.add(userId,rechargeInfo.getRechargeAmount());

		if(rows<=0){
			throw new GuiguException(400, "充值异常");
		}

		// 新增日志修改
		this.insertUserDetail(userId,
				"充值：" + rechargeInfo.getRechargeAmount(),
				SystemConstant.ACCOUNT_TRADE_TYPE_DEPOSIT,
				rechargeInfo.getRechargeAmount(),
				orderNo
				);

		//修改充值信息为已支付
		rechargeInfo.setRechargeStatus(SystemConstant.ORDER_STATUS_PAID);
		rechargeInfoMapper.insert(rechargeInfo);
	}


	/**
	 * 分页查询当前用户充值记录
	 * @param userAccountDetailPage
	 * @param userId
	 * @return
	 */
	@Override
	public Page<UserAccountDetail> getUserRechargePage(Page<UserAccountDetail> userAccountDetailPage, String s) {
		//查询的订单明细表
		Long userId = AuthContextHolder.getUserId();
		LambdaQueryWrapper<UserAccountDetail> queryWrapper1 = new LambdaQueryWrapper<>();
		queryWrapper1.eq(UserAccountDetail::getUserId,userId);
		queryWrapper1.eq(UserAccountDetail::getTradeType,s);
		queryWrapper1.orderByDesc(UserAccountDetail::getId);
		//执行查询
		Page<UserAccountDetail> userAccountDetailPage1 = userAccountDetailMapper.selectPage(userAccountDetailPage, queryWrapper1);

		return userAccountDetailPage1 ;
	}

	private void insertUserDetail(Long userId, String title, String tradeType, BigDecimal amount , String orderNo) {

		UserAccountDetail userAccountDetail = new UserAccountDetail();
		userAccountDetail.setUserId(userId);
		userAccountDetail.setTitle(title);
		userAccountDetail.setTradeType(tradeType);
		userAccountDetail.setAmount(amount);
		userAccountDetail.setOrderNo(orderNo);
		userAccountDetail.setCreateTime(new Date());

		userAccountDetailMapper.insert(userAccountDetail);
	}
}
